import axios from "axios";
import { ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
import { useUserStore } from "@/store/user";
import { goto } from "@/router";
import * as Login from "@/api/login";
import _ from "lodash";
const errorCode = {
  "401": "认证失败，无法访问系统资源",
  "403": "当前操作没有权限",
  "404": "访问资源不存在",
  default: "系统未知错误，请反馈给管理员",
};
// 用axios对象的create方法，创建一个axios实例
const request = axios.create({
  // 配置对象
  baseURL: import.meta.env.VITE_API_BASE_URL,
  // 请求超时时间
  timeout: 50000,
});
let isRefreshing = false;
let waitQueue: any[] = []; //刷新token期间等待请求
let failedQueue: any[] = []; //同期失败后请求

//token刷新成功
const processQueue = (error: any, token: string = "") => {
  waitQueue.forEach((item) => {
    if (error) {
      item.reject(error);
    } else {
      item.config.headers["Authorization"] = `Bearer ${token}`;
      item.reslove(item.config);
    }
  });
  failedQueue.forEach((item) => {
    if (error) {
      item.reject(
        JSON.stringify({
          msg: error,
        })
      );
    } else {
      item.config.headers["Authorization"] = `Bearer ${token}`;
      item.reslove(request(item.config));
    }
  });
};
// 过滤无效参数的函数
function filterParams(params: any) {
  const result: any = {};
  for (const key in params) {
    const value = params[key];
    // 过滤掉 null、空字符串、undefined、NaN 等无效值
    if (
      value !== null &&
      value !== "" &&
      value !== undefined &&
      !(typeof value === "number" && isNaN(value))
    ) {
      result[key] = value;
    }
  }
  return result;
}
// 请求拦截器重发请求注意，config的载荷可能被修改过不再是原始对象，需要转回对象
request.interceptors.request.use((config: any) => {
  if (config.params) {
    config.params = filterParams(config.params);
  }
  if (config.data) {
    config.data = filterParams(config.data);
  }
  const { authToken } = storeToRefs(useUserStore());
  if (authToken.value) {
    config.headers["Authorization"] = `Bearer ${authToken.value}`;
  }
  //要挂起时排除刷新token接口
  if (isRefreshing && !config.url.includes("/refreshToken")) {
    //挂起过期后发起的请求
    return new Promise((reslove: any, reject: any) => {
      const config_new = _.cloneDeep(config);
      if (
        typeof config_new.data === "string" &&
        config_new.headers &&
        config_new.headers["Content-Type"] &&
        config_new.headers["Content-Type"].includes("application/json")
      ) {
        config_new.data = JSON.parse(config_new.data);
      }
      waitQueue.push({ reslove, config: config_new, reject });
    });
  } else {
    return config;
  }
});
// 响应拦截器
request.interceptors.response.use(
  async (response: any) => {
    const { code } = response.data;
    const config = _.cloneDeep(response.config);
    const { setToken, setRefreshToken, clearToken, cleanRefreshToken } =
      useUserStore();
    if (code == 401) {
      //未登录
      console.log("未登录");
      clearToken();
      cleanRefreshToken();
      goto("Login");
    } else if (code == 403) {
      if (!isRefreshing) {
        isRefreshing = true;
        const { refreshAuthToken } = storeToRefs(useUserStore());
        //token过期，刷新
        console.log("token过期刷新中");
        try {
          const res = await Login.refreshToken({
            refreshToken: refreshAuthToken.value,
          });
          setToken(res.token);
          setRefreshToken(res.refreshToken);
          processQueue(null, res.token);
          config.headers["Authorization"] = `Bearer ${res.token}`;
          if (
            typeof config.data === "string" &&
            config.headers &&
            config.headers["Content-Type"] &&
            config.headers["Content-Type"].includes("application/json")
          ) {
            config.data = JSON.parse(config.data);
          }
          return request(config); //立马发起得到过期的请求
        } catch (error: any) {
          clearToken();
          cleanRefreshToken();
          processQueue("访问失效，请重新登录");
          goto("Login");
          return Promise.reject(JSON.stringify(error.data));
        } finally {
          isRefreshing = false;
        }
        console.log("问题来了")
      } else {
        //挂起失败后的请求
        return new Promise((reslove: any, reject: any) => {
          if (
            typeof config.data === "string" &&
            config.headers &&
            config.headers["Content-Type"] &&
            config.headers["Content-Type"].includes("application/json")
          ) {
            config.data = JSON.parse(config.data);
          }
          console.log(config,"谁到这了")
          failedQueue.push({
            reslove,
            config,
            reject,
          });
        });
      }
    }
    try {
      // 服务器响应成功，对数据处理
      if (response.data.code == 200) {
        // 检查是否是从登录接口返回的响应
        if (response.config.url.includes("/login")) {
          let token = response.headers["authorization"]; // 获取 token，根据实际情况调整字段名
          const { setToken, setRefreshToken } = useUserStore();
          if (token) {
            setToken(token.slice(7)); // 保存 token 到 store 中
          }
          const refreshToken = response.data.data.refreshToken;
          if (refreshToken) {
            setRefreshToken(refreshToken);
          }
        }
        return response.data;
      } else {
        const temp = JSON.parse(JSON.stringify(response.data));
        return Promise.reject(temp);
      }
    } catch (error: any) {
      ElMessage.error("系统异常中断!请联系管理员");
      throw "数据结构可能错误！";
    }
  },
  (error) => {
    console.log(error, "到达响应拦截错误");
    ElMessage.error(error);
    if (error == "访问失效，请重新登录") {
      const { clearToken, cleanRefreshToken } = useUserStore();
      clearToken();
      cleanRefreshToken();
      goto("Login");
    }
    // 响应失败的回调函数
    return Promise.reject(new Error(error));
  }
);
export default request;
